export default class SimpleArray<T> {
    private readonly maxLen: number;
    private readonly data: T[] = [];

    constructor(length: number) {
        this.maxLen = 0 < length ? length : 0;
    }

    public get length() {
        return this.maxLen;
    }

    public get(index: number): T | undefined {
        if (this.checkRange(index)) {
            return this.data[index];
        }
    }

    public set(index: number, value: T) {
        if (this.checkRange(index)) {
            this.data[index] = value;
        }
    }

    public clear() {
        this.data.splice(0, this.data.length);
    }

    public forEach(callback: (item: T, index?: number, array?: SimpleArray<T>) => void, thisArg?: any) {
        const maxLen = this.maxLen;
        const data = this.data;
        for (let index = 0; index < maxLen; index++) {
            callback.call(thisArg, data[index], index, this);
        }
    }

    public toString() {
        return JSON.stringify(this.data);
    }

    private checkRange(index: number): boolean {
        if (0 <= index && index < this.maxLen) {
            return true;
        } else {
            console.error(new RangeError('index out of range.'));
            return false;
        }
    }

    public static quickCreate<T>(...args: T[]): SimpleArray<T> {
        const arr = new SimpleArray<T>(args.length);
        arr.data.push(...args);
        return arr;
    }
}
